package com.itljm.cxrMarket.controller;

import com.itljm.cxrMarket.common.Result;
import com.itljm.cxrMarket.config.ModelMapperConfig;
import com.itljm.cxrMarket.mapper.SysMenuMapper;
import com.itljm.cxrMarket.entity.dto.MenuDto;
import com.itljm.cxrMarket.entity.SysMenu;
import com.itljm.cxrMarket.service.SysMenuService;
import com.itljm.cxrMarket.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ljm
 * @date 2024/12/11 9:34
 */
@RestController
@RequestMapping("/menu")
@CrossOrigin
//@Validated
public class SysMenuController {
    @Autowired
    private SysMenuService menuService;
    @Autowired
    private JwtUtil jwtUtil;

    @RequestMapping("/list")
    public Result queryMenuAll(){
        List<SysMenu> sysMenuList = menuService.queryMenuAll();
        return Result.ok(sysMenuList);
    }

    // 获取动态菜单
    @RequestMapping("/current/dynamic")
    public Result getDynamicMenu(){
        List<SysMenu> sysMenus = menuService.generateDynamicMenu();
        return Result.ok(sysMenus);
    }

    // 查询菜单树
    @RequestMapping("/trees")
    public Result queryMenuTree(){
        List<SysMenu> menus = menuService.queryMenuAll();
        ModelMapper modelMapper = ModelMapperConfig.createModelMapper();
        List<MenuDto> menuDtoList = menus.stream()
                .map(menu -> modelMapper.map(menu, MenuDto.class))
                .collect(Collectors.toList());
        Map<String, Object> buildTree = menuService.buildTree(menuDtoList);
        return Result.ok(buildTree);
    }

    // 查询当前用户菜单
    @RequestMapping("/current")
    public Result queryUserMenu(HttpServletRequest request){
        String token = request.getHeader("AccessToken");
        String userId;
        try {
            Claims claims = jwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            throw new BadCredentialsException("token非法，请重新登陆");
        }
        List<SysMenu> menus = menuService.queryMenuAll();
        return Result.ok(menus);
    }
}
